package com.service;

import com.registration.Register;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.List;

public class ServiceBuilder {

    Register register;
    StringUtil stringUtil;
    static final String prefixOfLock = "/locks";
    String localIp;

    {
        try {
            localIp = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public ServiceBuilder() throws UnknownHostException {
        this(2181,6666);
    }

    public ServiceBuilder(int registerPort,int nettyBindPort) throws UnknownHostException {
        register = new Register();
        register.start(registerPort);
        stringUtil = new StringUtil();
    }

    public void build(String servicePath, InetSocketAddress address) throws Exception {
        String lockPath = prefixOfLock+servicePath;
        String val = address.getHostString()+":"+address.getPort();
        InterProcessMutex readLock = new InterProcessReadWriteLock(register.curatorFramework,lockPath).readLock();
        readLock.acquire();
        register.createSequentialNode(servicePath+"/provider_",val);
        readLock.release();
    }

    public void deleteService(String servicePath, InetSocketAddress address) throws Exception{
        String lockPath = prefixOfLock+servicePath;
        InterProcessMutex writeLock = new InterProcessReadWriteLock(register.curatorFramework,lockPath).writeLock();
        writeLock.acquire();
        List<String> strings = register.retrieveCatalog(servicePath);
        if(strings.size()==1) {
            register.deleteAllNode(servicePath);
            writeLock.release();
            return;
        }
        String nowPath = servicePath+"/";
        for(int i=strings.size()-1;i>=0;i--){
            String newPath = nowPath+strings.get(i);
            String[] s = register.retrieveVal(newPath).split(":");
            if(s[0].equals(localIp)){
                register.deleteNode(newPath);
                break;
            }
        }
        writeLock.release();
    }

    public void close(){
        register.close();
    }
}